package com.example.airobotstatistics.service.impl;

import com.example.airobotstatistics.dto.InterviewStatisticsDto;
import com.example.airobotstatistics.service.InterviewStatisticsService;
import com.example.airobotstatistics.mapper.InterviewStatisticsMapper;
import com.example.candiates.service.InterviewCandidatesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 面试统计服务实现类
 */
@Service
public class InterviewStatisticsServiceImpl implements InterviewStatisticsService {

    private static final Logger logger = LoggerFactory.getLogger(InterviewStatisticsServiceImpl.class);

    @Autowired
    private InterviewStatisticsMapper interviewStatisticsMapper;

    @Autowired
    private InterviewCandidatesService candidatesService;

    @Override
    public InterviewStatisticsDto getInterviewStatistics(Integer positionId) {
        try {
            logger.info("获取面试统计数据 - 职位ID: {}", positionId);

            List<InterviewStatisticsDto> statisticsList = interviewStatisticsMapper.getInterviewStatistics(positionId);
            
            // 如果查询结果为空，创建一个空的统计对象
            if (statisticsList == null || statisticsList.isEmpty()) {
                InterviewStatisticsDto statistics = new InterviewStatisticsDto();
                statistics.setPositionId(positionId);
                statistics.setTotalInterviews(0);
                statistics.setPassedInterviews(0);
                statistics.setPassRate(0.0);
                statistics.setAverageDuration(0.0);
                statistics.setPendingInterviews(0);
                
                // 获取候选人总数
                long totalCandidates = candidatesService.count();
                statistics.setTotalCandidates((int) totalCandidates);
                
                // 获取所有面试数量
                Integer totalInterviews = interviewStatisticsMapper.getMonthlyInterviewCount(positionId);
                statistics.setMonthlyInterviews(totalInterviews != null ? totalInterviews : 0);
                
                // 获取已完成面试数量
                Integer completedInterviews = interviewStatisticsMapper.getCompletedInterviewCount(positionId);
                statistics.setCompletedInterviews(completedInterviews != null ? completedInterviews : 0);
                
                return statistics;
            }
            
            // 如果查询所有职位（positionId = 0），合并所有统计数据
            if (positionId == 0) {
                InterviewStatisticsDto mergedStatistics = new InterviewStatisticsDto();
                mergedStatistics.setPositionId(0);
                mergedStatistics.setPositionName("所有职位");
                mergedStatistics.setTotalInterviews(0);
                mergedStatistics.setPassedInterviews(0);
                mergedStatistics.setPendingInterviews(0);
                mergedStatistics.setAverageDuration(0.0);
                
                // 合并所有职位的统计数据
                for (InterviewStatisticsDto stat : statisticsList) {
                    mergedStatistics.setTotalInterviews(mergedStatistics.getTotalInterviews() + (stat.getTotalInterviews() != null ? stat.getTotalInterviews() : 0));
                    mergedStatistics.setPassedInterviews(mergedStatistics.getPassedInterviews() + (stat.getPassedInterviews() != null ? stat.getPassedInterviews() : 0));
                    mergedStatistics.setPendingInterviews(mergedStatistics.getPendingInterviews() + (stat.getPendingInterviews() != null ? stat.getPendingInterviews() : 0));
                    // 平均时长取所有职位的平均值
                    if (stat.getAverageDuration() != null) {
                        mergedStatistics.setAverageDuration(mergedStatistics.getAverageDuration() + stat.getAverageDuration());
                    }
                }
                
                // 计算平均时长
                if (!statisticsList.isEmpty()) {
                    mergedStatistics.setAverageDuration(mergedStatistics.getAverageDuration() / statisticsList.size());
                }
                
                // 获取候选人总数
                long totalCandidates = candidatesService.count();
                mergedStatistics.setTotalCandidates((int) totalCandidates);
                
                // 获取所有面试数量
                Integer totalInterviews = interviewStatisticsMapper.getMonthlyInterviewCount(positionId);
                mergedStatistics.setMonthlyInterviews(totalInterviews != null ? totalInterviews : 0);
                
                // 获取已完成面试数量
                Integer completedInterviews = interviewStatisticsMapper.getCompletedInterviewCount(positionId);
                mergedStatistics.setCompletedInterviews(completedInterviews != null ? completedInterviews : 0);
                
                logger.info("合并后的统计结果 - 总面试数: {}, 面试总数: {}, 候选人总数: {}, 已完成面试数: {}", 
                    mergedStatistics.getTotalInterviews(), mergedStatistics.getMonthlyInterviews(), 
                    mergedStatistics.getTotalCandidates(), mergedStatistics.getCompletedInterviews());
                
                return mergedStatistics;
            }
            
            // 如果查询特定职位，返回该职位的统计数据
            InterviewStatisticsDto statistics = statisticsList.get(0);
            
            // 获取候选人总数
            long totalCandidates = candidatesService.count();
            statistics.setTotalCandidates((int) totalCandidates);
            
            // 获取所有面试数量
            Integer totalInterviews = interviewStatisticsMapper.getMonthlyInterviewCount(positionId);
            statistics.setMonthlyInterviews(totalInterviews != null ? totalInterviews : 0);
            
            // 获取已完成面试数量
            Integer completedInterviews = interviewStatisticsMapper.getCompletedInterviewCount(positionId);
            statistics.setCompletedInterviews(completedInterviews != null ? completedInterviews : 0);
            
            logger.info("统计结果 - 总面试数: {}, 面试总数: {}, 候选人总数: {}, 已完成面试数: {}", 
                statistics.getTotalInterviews(), statistics.getMonthlyInterviews(), 
                statistics.getTotalCandidates(), statistics.getCompletedInterviews());
            
            return statistics;
        } catch (Exception e) {
            logger.error("获取面试统计数据失败", e);
            throw new RuntimeException("获取面试统计数据失败: " + e.getMessage());
        }
    }

    @Override
    public Integer getMonthlyInterviewCount(Integer positionId) {
        try {
            logger.info("获取面试数量 - 职位ID: {}", positionId);
            Integer count = interviewStatisticsMapper.getMonthlyInterviewCount(positionId);
            logger.info("面试数量: {}", count);
            return count != null ? count : 0;
        } catch (Exception e) {
            logger.error("获取面试数量失败", e);
            return 0;
        }
    }
} 